package com.stay.emoticon;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.stay.emoticon.EmoticonView.OnEmoticonTapListener;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */

	MyAdapter md = null;
	EmoEditText et = null;
	ListView list12 = null;

	// ����
	private LinearLayout root;
	private EmoticonView emoticon;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		root = (LinearLayout) findViewById(R.id.root);
		OnEmoticonTapListener onEmoticonTapListener = new OnEmoticonTapListener() {
			@Override
			public void onEmoticonTap(int drawableId) {
				// ImageGetter imageGetter = new ImageGetter() {
				// public Drawable getDrawable(String source) {
				// // int id = Integer.parseInt(source);
				// // Drawable d = getResources().getDrawable(id);
				// EmoticonDrawalbe d = new EmoticonDrawalbe(MainActivity.this, source);
				// d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				// return d;
				// }
				// };
				// CharSequence cs1 = Html.fromHtml("<img src='" + drawableId + "'/>", imageGetter, null);
				// int index = et.getSelectionStart();
				// Editable etb = et.getText();
				// int length = etb.length();
				// if (index < length) {
				// CharSequence cs = etb.subSequence(0, length);
				// CharSequence cs2 = cs.subSequence(0, index);
				// CharSequence cs3 = cs.subSequence(index, length);
				// et.setText(null);
				// et.append(cs2);
				// et.append(cs1);
				// et.append(cs3);
				// } else {
				// et.append(cs1);
				// }
				// et.setSelection(index + 1);
				if (drawableId <= R.drawable.mr_182 && drawableId >= R.drawable.mr_100) {
					// <img src="http://pic.jjdd.com/v1/i/pub/face/kb/122.gif" class="ico">
					et.addImg("http://pic.jjdd.com/v1/i/pub/face/mr/"
							+ (drawableId - R.drawable.mr_100 + 100) + ".gif", drawableId,
							MainActivity.this);
				}
			}
		};
		emoticon = new EmoticonView(this, onEmoticonTapListener);
		emoticon.setVisibility(View.GONE);
		root.addView(emoticon);

		list12 = (ListView) findViewById(R.id.ListView01);
		ArrayList<CharSequence> a = new ArrayList<CharSequence>();
		md = new MyAdapter(this, a);
		list12.setAdapter(md);

		et = (EmoEditText) findViewById(R.id.EditText01);
		Button button = (Button) this.findViewById(R.id.Button01);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				add();
				et.clearAnimate();
			}
		});

		final Button button3 = (Button) this.findViewById(R.id.Button03);
		final Button button2 = (Button) this.findViewById(R.id.Button02);

		button3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				InputMethodManager m = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				m.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
				emoticon.setVisibility(View.GONE);
				button2.setVisibility(View.VISIBLE);
				button3.setVisibility(View.GONE);
			}
		});

		button2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				emoticon.setVisibility(View.VISIBLE);
				button3.setVisibility(View.VISIBLE);
				button2.setVisibility(View.GONE);
				// ������̹ر�
				InputMethodManager m = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				m.hideSoftInputFromWindow(et.getApplicationWindowToken(), 0);
				// m.toggleSoftInput(0, InputMethodManager.RESULT_UNCHANGED_HIDDEN);

				// onClick_RandomInsertFace(faces[new Random().nextInt(faces.length)]);
			}
		});

		et.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				button2.setVisibility(View.VISIBLE);
				button3.setVisibility(View.GONE);
				emoticon.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (emoticon.onKeyDown(keyCode, event)) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * ʮ����Ҫ ��ͼƬת��ΪCharSequence
	 */
	private void add() {
		Editable etb = et.getText();
		if (etb.length() == 0) {
			et.setError("null");
		} else {
			CharSequence cs = etb.subSequence(0, etb.length());
			SpannableStringBuilder ssb = new SpannableStringBuilder(cs);
			ImageSpan[] spans = ssb.getSpans(0, cs.length(), ImageSpan.class);
			for (int i = 0; i < spans.length; i++) {
				ImageSpan span = spans[i];
				String c = span.getSource();
				int a = ssb.getSpanStart(span);
				int b = ssb.getSpanEnd(span);
				ssb.replace(a, b, "<img src=\"" + c + "\" class=\"ico\">");
			}
			ssb.clearSpans();
			String d = ssb.toString();
			md.add(cs);
			et.setText(null);
		}

	}

	SpannableString ss = null;

	/**
	 * ������� ������� ֮ǰ���ϵĿ����ģ���editText �в���ͼƬ�������� ������û���õ���
	 * 
	 * @param id
	 * @return
	 */
	public SpannableString insertIcon(int id) {
		ss = new SpannableString("[smile]");
		Drawable d = getResources().getDrawable(id);
		d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
		ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
		ss.setSpan(span, 0, "[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		// et.setText(ss);
		return ss;
	}

	/**
	 * listView
	 * 
	 * @author Administrator
	 * 
	 */
	class MyAdapter extends BaseAdapter {

		Context cont = null;
		LayoutInflater lf = null;
		ArrayList<CharSequence> a = null;
		private com.stay.emoticon.MainActivity.ViewHolder holder;

		// int[] faces = new int[] { R.drawable.icon, R.drawable.img1,
		// R.drawable.img2, R.drawable.img3, R.drawable.img4, };

		public MyAdapter(Context context, ArrayList<CharSequence> a) {

			this.cont = context;
			this.lf = LayoutInflater.from(cont);
			this.a = a;
		}

		public int getCount() {

			return a.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return a.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView.getTag() == null) {
				holder = new ViewHolder();
				convertView = lf.inflate(R.layout.arrlayout, null);
				holder.et = (EmoTextView) convertView.findViewById(R.id.EditView02);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.et.setText(a.get(position));
			holder.et.prepareAnimate();
			return convertView;
		}

		public void add(CharSequence str) {
			a.add(str);
			notifyDataSetChanged();
		}

		public void clear() {
			a.clear();
			notifyDataSetChanged();
		}
	}

	static class ViewHolder {
		public EmoTextView et;
	}
	// CharSequence cs = Html.fromHtml("<img src='" + mThumbIds[position]+ "'/>",imageGetter, null);
	// etContent.getText().append(cs);
	// faceContent =FilterHtml(Html.toHtml(etContent.getText()));
	//
	// public static String FilterHtml(String str){
	// str = str .replaceAll("<(?!br|img)[^>]+>", "").trim();
	// return UnicodeToGBK2(str);
	// }
	//
	//
	// public static String UnicodeToGBK2(String s){
	// String[] k = s.split(";") ;
	// String rs = "" ;
	// for(int i=0;i<k.length;i++) {
	// int strIndex=k.indexOf("&#");
	// String newstr = k;
	// if(strIndex>-1) {
	// String kstr = "";
	// if(strIndex>0) {
	// kstr = newstr.substring(0,strIndex);
	// rs+=kstr;
	// newstr = newstr.substring(strIndex);
	// }
	// int m = Integer.parseInt(newstr.replace("&#",""));
	// char c = (char)m ;
	// rs+= c ;
	// } else {
	// rs+=k;
	// }
	// }
	// return rs;
	// }

}
